/*
 * 一些工具
 */
import validator from './validator'
import { Message } from 'element-ui'
/**
 * @param {Object,String} val
 * @returns {Boolean}
 */
export function isValid(val) {
  return (
    val !== null && val !== 'null' && val !== undefined && val !== 'undefined'
  )
}

/**
 * 清除object无效key
 * @param {Object} obj
 * @returns {Object}
 */
export function clearObject(obj) {
  const newObj = {}
  for (const i in obj) {
    const tmpProp = obj[i]
    if (tmpProp !== '' && isValid(obj)) {
      newObj[i] = tmpProp
    }
  }
  return newObj
}
/*
 * 基于validator的ele错误封装
 */
export function eleValidator(condition) {
  let nowCondition = {}
  nowCondition.rules = condition
  return async (rule, value, callback) => {
    nowCondition.value = value
    const validateResult = await validator([nowCondition])
    if (!validateResult.status) {
      callback(new Error(validateResult.msg))
    } else {
      callback()
    }
  }
}
/*
 * 接口错误提示
 */
export const apiError = err => {
  let errorMsg = '接口出错，请联系管理员'
  if (typeof err === 'string') {
    errorMsg = err
  } else if (typeof err === 'object' && err.message) {
    errorMsg = err.message
  }
  Message.error(errorMsg)
}
